package com.himiotech.core.project.web.support;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HtmlUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.himiotech.core.framework.helper.anno.Log;
import com.himiotech.core.framework.helper.enums.BusinessType;
import com.himiotech.core.framework.helper.model.XmSelectTree;
import com.himiotech.core.project.model.entity.gen.GenTable;
import com.himiotech.core.project.model.entity.gen.GenTableColumn;
import com.himiotech.core.project.service.IGenService;
import com.himiotech.core.project.service.IGenTableColumnService;
import com.himiotech.core.project.service.IGenTableService;
import com.himiotech.core.project.service.IMenuService;
import com.himiotech.core.project.web.base.HimioBaseController;
import com.himiotech.core.project.web.base.model.HimioResult;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Controller
@RequestMapping("/tool/gen")
public class GenController extends HimioBaseController {

    @Autowired
    private IGenService genService;
    @Autowired
    private IGenTableService genTableService;
    @Autowired
    private IGenTableColumnService genTableColumnService;
    @Autowired
    private IMenuService menuService;

    @RequiresPermissions("tool:gen:view")
    @GetMapping
    public String gen() {
        return "tool/gen";
    }

    /**
     * 查询代码生成列表
     */
    @RequiresPermissions("tool:gen:list")
    @PostMapping("/list")
    @ResponseBody
    public HimioResult genList(Page<GenTable> genTablePage, GenTable genTable) {
        handleOrderBy(request, genTablePage);
        genTablePage = genTableService.selectGenTableListPage(genTablePage, genTable);
        return writeJsonLayuiTable(genTablePage);
    }

    /**
     * 查询数据库列表
     */
    @RequiresPermissions("tool:gen:list")
    @PostMapping("/db/list")
    @ResponseBody
    public HimioResult dataList(Page<Map<String, Object>> genTablePage) {
        handleOrderBy(request, genTablePage);
        genTablePage = genService.tableTodoListPage(genTablePage, requestParamMap(request));
        return writeJsonLayuiTable(genTablePage);
    }

    /**
     * 查询数据表字段列表
     */
    @RequiresPermissions("tool:gen:list")
    @PostMapping("/column/list")
    @ResponseBody
    public HimioResult columnList(GenTableColumn genTableColumn) {
        Page<GenTableColumn> genTableColumnPage = new Page<>(1, 200);
        List<GenTableColumn> records = genTableColumnService.selectGenTableColumnListByTableId(genTableColumn);
        return writeJsonLayuiTable(genTableColumnPage, records);
    }


    /**
     * 导入表结构
     */
    @RequiresPermissions("tool:gen:list")
    @GetMapping("/importTable")
    public String importTable() {
        return "tool/import";
    }

    /**
     * 导入表结构（保存）
     */
    @RequiresPermissions("tool:gen:list")
    @Log(title = "代码生成 - 导入表结构", businessType = BusinessType.IMPORT)
    @PostMapping("/importTable")
    @ResponseBody
    public HimioResult importTableSave(String tables) {
        String[] tableNames = Convert.toStrArray(tables.split(","));
        //查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return writeJsonOk();
    }

    /**
     * 修改代码生成业务
     */
    @GetMapping("/edit")
    public String edit(Long tableId, ModelMap mmp) {
        GenTable table = genTableService.selectGenTableById(tableId);
        List<XmSelectTree> xmSelectTrees = menuService.menuTreeData();
        mmp.put("table", table);
        mmp.put("allMenu", xmSelectTrees);
        return "tool/edit";
    }

    /**
     * 修改保存代码生成业务
     */
    @RequiresPermissions("tool:gen:edit")
    @Log(title = "代码生成 - 修改生成配置", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public HimioResult editSave(@Validated GenTable genTable) {
        //此步主要是校验 树形表以及父子表的相关数据
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return writeJsonOk();
    }

    /**
     * 修改保存代码生成业务
     */
    @RequiresPermissions("tool:gen:edit")
    @Log(title = "代码生成 - 修改生成字段配置", businessType = BusinessType.UPDATE)
    @PostMapping("/editColumn")
    @ResponseBody
    public HimioResult editColComment(GenTableColumn genTableColumn) {
        genTableColumnService.updateById(genTableColumn);
        return writeJsonOk();
    }


    /**
     * 删除
     */
    @RequiresPermissions("tool:gen:remove")
    @Log(title = "代码生成 - 删除配置", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public HimioResult remove(String ids) {
        genTableService.deleteGenTableByIds(ids);
        return writeJsonOk();
    }

    /**
     * 预览代码
     */
    @RequiresPermissions("tool:gen:preview")
    @GetMapping("/preview/{tableId}")
    @ResponseBody
    public HimioResult preview(@PathVariable("tableId") Long tableId) throws IOException {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        dataMap.replaceAll((k, v) -> HtmlUtil.escape(v));
        return writeJsonOk("获取数据成功", dataMap);
    }

    /**
     * 生成代码（自定义路径）
     */
    @RequiresPermissions("tool:gen:code")
    @Log(title = "代码生成", businessType = BusinessType.GENCODE)
    @GetMapping("/genCode/{tableName}")
    @ResponseBody
    public HimioResult genCode(@PathVariable("tableName") String tableName) {
        genTableService.generatorCode(tableName);
        return writeJsonOk("生成代码成功，请前往工程目录查看");
    }

    /**
     * 同步数据库
     */
    @RequiresPermissions("tool:gen:edit")
    @Log(title = "代码生成", businessType = BusinessType.UPDATE)
    @GetMapping("/syncDb/{tableName}")
    @ResponseBody
    public HimioResult syncDb(@PathVariable("tableName") String tableName) {
        genTableService.syncDb(tableName);
        return writeJsonOk();
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}